package com.zte.cl.utils;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import org.apache.log4j.Logger;

import sun.misc.BASE64Decoder;


public class StringUtil {
	private static final Logger loggerService = Logger.getLogger(StringUtil.class);
	
	public static String subString(String str, int endIndex) {
		if (null == str || str.length() <= endIndex) {
			return str;
		} else {
			return str.substring(0, endIndex);
		}
	}

	/**
	 * @param value
	 * @param replaceString超长部分替换
	 * @return
	 */
	public static String subStringChinese(String value, String replaceString, int maxLength) {
		try {
			if (value.length() > maxLength) {
				float curSize = 0;
				StringBuffer sb = new StringBuffer("");
				char[] charArray = value.toCharArray();
				for (int j = 0; j < charArray.length; j++) {
					String str = String.valueOf(charArray[j]);

					if (str.getBytes("utf-8").length == 1) {
						curSize += 0.5;
					} else {
						curSize += 1;
					}
					if (curSize <= maxLength) {
						sb.append(str);
					} else {
						sb.append(replaceString);
						break;
					}
				}
				value = sb.toString();
			}
		} catch (Exception e) {
			loggerService.error("截取字符串异常", e);
		}
		return value;
	}

	/**
	 * 把文件分类列表转成定数字符串显示
	 * 
	 * @param list
	 * @return
	 */

	public static String getFileTextTention(String fileName) {
		if (fileName != null) {
			String[] arr = fileName.split(".");
			if (arr[0].equals("*") && arr.length == 2) {
				return arr[1];
			}
		}
		return null;
	}

	public static String converArrayString(String name, String strsname) {
		StringBuffer str = new StringBuffer();
		boolean fal = false;
		String[] strs = strsname.split(",");
		for (int i = 0; i < strs.length; i++) {
			if (strs[i].equals(name) || strs[i] == name) {
				fal = true;
				break;
			}

		}
		if (fal) {
			for (int i = 0; i < strs.length; i++) {
				if (!strs[i].equals(name) || strs[i] != name) {
					if (i == strs.length - 1) {
						str.append(strs[i]);
					} else {
						str.append(strs[i]).append(",");
					}
				}
			}
		} else {
			for (int i = 0; i < strs.length; i++) {
				str.append(strs[i]).append(",");
			}
			str.append(name);
		}

		return str.toString();
	}

	/**
	 * 判断不为NUL和不为空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isEmpty(String str) {
		return str == null || "".equals(str.trim()) || "null".equals(str.trim().toLowerCase());
	}

	/**
	 * 将字符串首字母转换为大写
	 * 
	 * @param s
	 * @return
	 */
	public static String toUpperCaseFirstOne(String s) {
		if (Character.isUpperCase(s.charAt(0)))
			return s;
		else
			return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
	}

	/**
	 * 用UTF-8解码
	 * 
	 * @param str
	 * @return
	 */
	public static String Base64Decode(String str, String encoding) {
		if (str != null) {
			BASE64Decoder decode = new BASE64Decoder();
			try {
				str = str.replaceAll("%2B", "+");
				str = str.replaceAll("%2F", "/");
				str = str.replaceAll("%3D", "=");
				str = new String(decode.decodeBuffer(str), encoding);
				return str;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 去除带分割符","里的重复ID
	 * 
	 * @param str
	 * @return
	 */
	public static String removeRepeate(String str) {
		String[] arr = str.split(",");
		if (arr.length == 1)
			return str;
		List<String> list = new LinkedList<String>();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < arr.length; i++) {
			if (!list.contains(arr[i]) && !"".equals(arr[i]))
				list.add(arr[i]);
		}
		for (int i = 0; i < list.size(); i++) {
			if (i != 0)
				buf.append(",");
			buf.append(list.get(i));
		}
		return buf.toString();
	}

	/**
	 * 合并ID字符串，并去除重复
	 * 
	 * @param str1
	 * @param str2
	 * @return
	 */
	public static String mergeIdStr(String str1, String str2, boolean removeRepate) {
		StringBuffer buf = new StringBuffer();
		if (!StringUtil.isEmpty(str1)) {
			buf.append(str1);
		}
		if (!StringUtil.isEmpty(str1) && !StringUtil.isEmpty(str2)) {
			buf.append(",");
		}
		if (!StringUtil.isEmpty(str2)) {
			buf.append(str2);
		}
		String str = buf.toString();
		if (removeRepate) {
			str = removeRepeate(str);
		}
		return str;
	}

	public static boolean isNumeric(String str) {
		for (int i = str.length(); --i >= 0;) {
			if (!Character.isDigit(str.charAt(i))) {
				return false;
			}
		}
		return true;
	}

	/**
	 * 将<,>,&,解析为ASCII码
	 * 
	 * @param str
	 * @return
	 */
	public static String decodedHtml(String str) {

		if (str.contains("<")) {
			str = str.replace("<", "&lt;");
		}
		if (str.contains(">")) {
			str = str.replace(">", "&gt;");
		}
		return str;
	}

	public static String toEmptyOrTrim(String s) {
		return (s == null ? "" : s.trim());
	}

	/**
	 * 在一个字符串前，补0，返回一个定长的字符串
	 * 
	 * @param src
	 * @param length
	 * @return
	 */
	public static String insertZeroBeforeString(String src, int length) {
		StringBuffer sb = new StringBuffer();
		int leftLen = length - src.length();
		for (int i = 0; i < leftLen; i++)
			sb.append("0");
		sb.append(src);
		return sb.toString();
	}

	public static String objectToString(Object o) {
		return (o == null ? "" : o.toString());
	}
	
	/**
	 * 功能：把Object转为String再转int
	 * */
	public static int ObjStringToInt(Object obj) {
		int $return = 0;
		if (ValidatorUtil.isNotNull(obj)) {
			String objstr = String.valueOf(obj);
			if (ValidatorUtil.isInteger(objstr)) {
				$return = Integer.valueOf(objstr);
			}
		}
		return $return;
	}

	/**
	 * 功能：把Object转为String再转Integer
	 * */
	public static Integer ObjStringToInteger(Object obj) {
		int $return = 0;
		if (ValidatorUtil.isNotNull(obj)) {
			String objstr = String.valueOf(obj);
			if (ValidatorUtil.isInteger(objstr)) {
				$return = Integer.valueOf(objstr);
			}
		}
		return $return;
	}
	

	/**
	 * 随机验证码生成
	 * 
	 * @param type
	 *            0:纯数字， 1：纯字母， 其他：数字字母混合
	 * @param len
	 *            验证码长度
	 * @return
	 */
	public static String generateCode(int type, int len) {
		Random random = new Random();
		String randString;
		if (type == 0) {
			randString = "0123456789";
		} else if (type == 1) {
			randString = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		} else {
			randString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		}
		String randomString = "";
		for (int i = 1; i <= len; i++) {
			String rand = String.valueOf(randString.charAt(random.nextInt(randString.length())));
			randomString += rand;
		}
		return randomString;
	}

	public static String getBaseUrl(String requestUrl) {
		String baseUrl = null;
		if (requestUrl.length() > 7 && requestUrl.startsWith("http://")) {
			requestUrl = requestUrl.substring(7);
			int end = requestUrl.indexOf("/");
			if (end == -1) {
				baseUrl = "http://" + requestUrl + "/";
			} else {
				baseUrl = "http://" + requestUrl.substring(0, end + 1);
			}
		} else if (requestUrl.length() > 8 && requestUrl.startsWith("https://")) {
			requestUrl = requestUrl.substring(8);
			int end = requestUrl.indexOf("/");
			if (end == -1) {
				baseUrl = "https://" + requestUrl + "/";
			} else {
				baseUrl = "https://" + requestUrl.substring(0, end + 1);
			}
		}
		// System.out.println(baseUrl);
		return baseUrl;
	}

	/**
	 * 遍历实体类的属性和数据类型以及属性值
	 * 
	 * @param model
	 * @throws NoSuchMethodException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static String reflectField(Object model) throws NoSuchMethodException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		StringBuffer sbStr = new StringBuffer();
		// 获取实体类的所有属性，返回Field数组
		Field[] field = model.getClass().getDeclaredFields();
		// 遍历所有属性
		for (int j = 0; j < field.length; j++) {
			// 获取属性的名字
			String name = field[j].getName();
			// 将属性的首字符大写，方便构造get，set方法
			name = name.substring(0, 1).toUpperCase() + name.substring(1);
			// 获取属性的类型
			String type = field[j].getGenericType().toString();
			// 如果type是类类型，则前面包含"class "，后面跟类名
			if (type.equals("class java.lang.String")) {
				Method m = model.getClass().getMethod("get" + name);
				// 调用getter方法获取属性值
				String value = (String) m.invoke(model);
				sbStr.append(String.format("%s=%s", value != null ? value : ""));
			} else if (type.equals("class java.lang.Integer")) {
				Method m = model.getClass().getMethod("get" + name);
				Integer value = (Integer) m.invoke(model);
				sbStr.append(String.format("%s=%s", value != null ? value : ""));
			} else if (type.equals("class java.lang.Short")) {
				Method m = model.getClass().getMethod("get" + name);
				Short value = (Short) m.invoke(model);
				sbStr.append(String.format("%s=%s", value != null ? value : ""));
			} else if (type.equals("class java.lang.Double")) {
				Method m = model.getClass().getMethod("get" + name);
				Double value = (Double) m.invoke(model);
				sbStr.append(String.format("%s=%s", value != null ? value : ""));
			} else if (type.equals("class java.lang.Boolean")) {
				Method m = model.getClass().getMethod("get" + name);
				Boolean value = (Boolean) m.invoke(model);
				sbStr.append(String.format("%s=%s", value != null ? value : ""));
			} else if (type.equals("class java.util.Date")) {
				Method m = model.getClass().getMethod("get" + name);
				Date value = (Date) m.invoke(model);
				sbStr.append(String.format("%s=%s", value != null ? value : ""));
			}
		}
		return sbStr.toString();
	}

	public static boolean isNullStr(String s) {
		if (s == null || s.trim().equals("") || s.trim().toLowerCase().equals("null")) {
			return true;
		}
		return false;
	}
	
	public static boolean equals(String s1, String s2, boolean caseSensitive) {
		if (caseSensitive) {
			return s1.equals(s2) ? true : false;
		} else {
			return s1.toUpperCase().equals(s2.toUpperCase()) ? true : false;
		}
	}
	
	/** 
	 
     * 相似度比较 
     * @param strA 
     * @param strB 
     * @return 
     */  
    public static double SimilarDegree(String strA, String strB){  
        String newStrA = removeSign(strA); 
        String newStrB = removeSign(strB);
  
        int temp = Math.max(newStrA.length(), newStrB.length());
        int temp2 = 0;
        if(newStrA.length() == temp) {
        	temp2 = longestCommonSubstring(newStrA, newStrB).length(); 
        } else {
        	temp2 = longestCommonSubstring(newStrB, newStrA).length(); 
        }
  
        return temp2 * 1.0 / temp;  
    } 
    
    private static String removeSign(String str) {  
        StringBuffer sb = new StringBuffer();  
  
        for (char item : str.toCharArray()) {
        	 if (charReg(item)){  
                 sb.append(item);  
             } 
        }
        return sb.toString();  
    } 
    
    private static boolean charReg(char charValue) {  
        return (charValue >= 0x4E00 && charValue <= 0X9FA5)  
  
                || (charValue >= 'a' && charValue <= 'z')  
  
                || (charValue >= 'A' && charValue <= 'Z')  
  
                || (charValue >= '0' && charValue <= '9');  
  
    }
    
    private static String longestCommonSubstring(String strA, String strB) {  
        char[] chars_strA = strA.toCharArray();  
        char[] chars_strB = strB.toCharArray();  
  
        int m = chars_strA.length;  
        int n = chars_strB.length;  
  
        int[][] matrix = new int[m + 1][n + 1];  
        for (int i = 1; i <= m; i++) {  
            for (int j = 1; j <= n; j++) { 
                if (chars_strA[i - 1] == chars_strB[j - 1])  
                    matrix[i][j] = matrix[i - 1][j - 1] + 1;  
                else  
                    matrix[i][j] = Math.max(matrix[i][j - 1], matrix[i - 1][j]);  
            }  
        }  
  
        char[] result = new char[matrix[m][n]];  
        int currentIndex = result.length - 1;  
        while (matrix[m][n] != 0) {
            if (matrix[n] == matrix[n - 1])  
                n--;  
            else if (matrix[m][n] == matrix[m - 1][n])   
                m--;  
            else {  
                result[currentIndex] = chars_strA[m - 1];  
                currentIndex--;  
                n--;  
                m--;  
            }  
        }  
  
        return new String(result);  
    }
    
    public static String processNullStr(String s) {
    	if(s == null || s.trim().equals("") || s.trim().toLowerCase().equals("null")) {
    		return "";
    	}
    	return s;
    }
}
